<?php
/**
 * 数据库备份逻辑层
 * @author maniac
 */
namespace app\common\logic;

use app\facade\UserLogs;
use think\Db;

class Dump extends Base
{
    /**
     * 备份数据库
     * @param  array $data 请求的信息
     */
    public function save($data)
    {
        if (!trim($data['filename'])) {
            exception('请输入存放目录');
        }
        $bak_path = str_replace("\\", "/", \think\Facade\Env::get('app_path')) . request()->module() . '/datas/bak/';
        
        if (!is_dir($bak_path)) {
            mkdir($bak_path, 0755, true);
        }
        $fileName  = $bak_path . unid() . '_' . $data['filename'];
        $createSql = $this->data2sql();
        file_put_contents($fileName, $createSql);
        
        if (file_exists($fileName)) {
            UserLogs::insertLog(['title' => '备份数据']);
            return true;
        }
        exception('备份数据失败');
    }
    
    /**
     * 组装 sql 备份语句
     */
    private function data2sql()
    {
        // 获取所有数据表
        $tables    = Db::query("SHOW TABLES");
        $createSql = '';
        // 数据库名称
        $database  = config('database.database');
        foreach ($tables as $v) {
            // 数据表名称
            $table      = $v['Tables_in_'.$database];
            $temp       = Db::query("SHOW CREATE TABLE {$table}");
            $createSql .= $temp[0]['Create Table']."\n\n";
            $fields     = get_fields(str_replace(config('database.prefix'), '', $table));
            $data       = Db::query("SELECT * FROM {$table}");
            
            foreach ($data as $val) {
                $values = '';
                foreach ($fields as $field) {
                    $values .= "'".str_replace("'", "\\'", $val[$field])."',";
                }
                $values = trim($values, ',');
                $createSql .= "INSERT INTO {$table} VALUES ({$values});\n\n";
            }
        }
        return $createSql;
    }
}
